package kevin.hbase.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpsUtil {

    private static String result;
    private static String TLS = "TLS";
    private static String GET = "GET";
    private static String POST = "POST";

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static final String HEADER_CONTENT_JSON = "application/json";

    private static CloseableHttpClient httpClient;

    private static ObjectMapper mapper = new ObjectMapper();

    private static final String HTTP = "http";

    private static final String HTTPS = "https";

    private static SSLContextBuilder sslContextBuilder = null;


    /**
     * 记录开放平台请求结果
     */
    public static class Response {
        /**
         * 该请求的 http 状态码
         * 200 为正常的返回结果
         */
        private int status;

        /**
         * 请求返回消息
         * 当 status == 200 时会返回 response body 中的字符串
         * 当 status !== 200 时会返回具体的错误信息
         */
        private String result;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }
    }

    static {
        try {
            RequestConfig globalConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(200000)
                    .setConnectTimeout(200000)
                    .setSocketTimeout(500000)
                    .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                    .build();
            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            sslContextBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registryBuilder);
            poolingHttpClientConnectionManager.setMaxTotal(500);
            poolingHttpClientConnectionManager.setDefaultMaxPerRoute(50);
            httpClient = httpClientBuilder
                    .setSSLSocketFactory(sslConnectionSocketFactory)
                    .setConnectionManager(poolingHttpClientConnectionManager)
                    .setDefaultRequestConfig(globalConfig)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized static CloseableHttpClient getCloseableHttpClient() {
        if (httpClient == null) {
            try {
                SSLConnectionSocketFactory sslConnectionSocketFactory = null;
                FileInputStream keyin = new FileInputStream(new File("d:\\client.p12"));
                KeyStore keystore = KeyStore.getInstance("PKCS12");
                keystore.load(keyin, "client1".toCharArray());
                keyin.close();
                final TrustStrategy trustStrategy = new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                };
                SSLContext sslcontext = SSLContexts.custom()
                        .loadTrustMaterial(trustStrategy)
                        .loadKeyMaterial(keystore, "client1".toCharArray())
                        .build();
                sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                        sslcontext,
                        SSLConnectionSocketFactory.getDefaultHostnameVerifier());


                Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", sslConnectionSocketFactory)
                        .build();
                PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
                connectionManager.setMaxTotal(200);
                connectionManager.setDefaultMaxPerRoute(20);
                HttpClientBuilder httpClientBuilder = HttpClients.custom();
//            if(sslConnectionSocketFactory!=null){
//                httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
//            }
                httpClientBuilder.setConnectionManager(connectionManager);
                httpClient = httpClientBuilder.build();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return httpClient;
    }


    private static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    public static <T> T doGet(String requestUrl, Map<String, String> paramMap, Class<T> type) throws IOException {
        return mapper.readValue(doGet(requestUrl, paramMap), type);
    }

    public static <T> T doGet(String requestUrl, Map<String, String> paramMap, TypeReference<T> typeReference) throws IOException {
        return mapper.readValue(doGet(requestUrl, paramMap), typeReference);
    }

    public static String doGet(String requestUrl, Map<String, String> paramMap) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        StringBuilder param = new StringBuilder("?");
        if (paramMap != null) {
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                param.append(entry.getKey());
                param.append("=");
                param.append(entry.getValue());
                param.append("&");
            }
            param.deleteCharAt(param.length() - 1);
        }

        HttpGet get = new HttpGet(requestUrl + param);
        String responseString = httpClient.execute(get, response -> EntityUtils.toString(response.getEntity()));
        get.releaseConnection();
        return responseString;
    }

}

